<?php
namespace app\admin\controller;
use app\admin\model\ApiGroup;
use think\Controller;
use think\Request;
use app\admin\model\Api as ApiModel;
use app\admin\model\ApiGroup as ApiGroupModel;
use app\admin\model\Param as ParamModel;


class Api extends Base
{

    //API列表
    public function index(){
        return $this->fetch();
    }

    //API数据源
    public function api_data(Request $request)
    {
        $page = $request->param('page');
        if(!$this->user_id){
            return ajaxReturn('请您登陆');
        }

        $user = '';
        if(!$this->isRoot()){
            $user = $this->user_id;
        }
        $model = new ApiModel();
        $list = $model->getApiList($page,$user);
        if(is_array($list) || is_object($list)){
            return ajaxReturn($list,$model->count);
        }else{
            return ajaxReturn('查询错误');
        }
    }

    //API查询单条数据
    public function api_edit_data(Request $request)
    {
        $id = $request->param('id');
        if(!$id){
            return ajaxReturn('参数错误');
        }
        $result = ApiModel::get($id);
        $result->requestData = $result->getData('request');
        $result->param = $result->params()->where(['type'=>0,'status'=>1])->select();
        $result->paramNum = count($result->param);
        $result->result = $result->params()->where(['type'=>1,'status'=>1])->select();
        $result->resultNum = count($result->result);
        $this->assign('list',$result);
        return ajaxReturn($result);
    }

    //根据类型获取参数列表
    public function api_param_data(Request $request)
    {
        $param = $request->param();
        if(!$request['id']){
            return ajaxReturn('参数错误');
        }
        $list = ParamModel::all(['status'=>1,'api_id'=>$param['id'],'type'=>$param['type']]);
        return ajaxReturn($list);
    }

    //API添加
    public function api_add(){
        return $this->fetch();
    }

    //API添加操作
    public function api_add_do(Request $request){
        if(!$this->auth()){
            return ajaxReturn('请先登陆再进行操作');
        }
        $model = new ApiModel();
        $params = $request->param();
        try{
            $model->startTrans();
            $model->data([
                'url'  =>  $params['url'],
                'name' =>  $params['name'],
                'group_id' => $params['group'],
                'request' => $params['request'],
                'param_explain' => $params['param_explain'],
                'result_text' => $params['result_text'],
                'result_explain' => $params['result_explain'],
                'user_id' => $this->user_id,
                'sort' => $params['sort'],
                'status' => $params['status']
            ]);
            $model->save();
            if($model->id){
                $data = [];
                $paramModel = new ParamModel();
                $paramList = $params['param'];
                if(is_array($paramList) && !empty($paramList)){
                    foreach($params['param'] as $k => $v){
                        $data[] = [
                            'api_id' => $model->id,
                            'param' => $v['param_name'],
                            'filed_type' => $v['param_type'],
                            'must' => $v['must'],
                            'type' => 0,
                            'explain' => $v['explain']
                        ];
                    }
                }
                if($data){
                    $paramModel->saveAll($data);
                }

                $data = [];
                $resultList = $params['result'];
                if(is_array($resultList) && !empty($resultList)){
                    foreach($params['result'] as $kk => $vv){
                        $data[] = [
                            'api_id' => $model->id,
                            'param' => $vv['param_name'],
                            'filed_type' => $vv['param_type'],
                            'must' => $vv['must'],
                            'type' => 1,
                            'explain' => $vv['explain']
                        ];
                    }
                }
                if($data){
                    $paramModel->saveAll($data);
                }
            }
        }catch(\Exception $e){
            $model->rollback();
            logs($e->getMessage());
            return ajaxReturn('API添加失败');
        }
        $model->commit();
        return ajaxReturn([],'添加成功');
    }

    //API编辑页面
    public function api_edit(Request $request)
    {
        $id = $request->param("id");
        $this->assign('id',$id);
        return $this->fetch();
    }

    //API编辑处理
    public function api_edit_do(Request $request)
    {
        if(!$this->auth()){
            return ajaxReturn('请先登陆再进行操作');
        }
        $params = $request->param();

        if(!isset($params['id']) || !intval($params['id'])){
            return ajaxReturn('参数错误');
        }

        $model = new ApiModel();
        try{
            $model->startTrans();
            $model->update([
                'id'  =>  $params['id'],
                'url'  =>  $params['url'],
                'name' =>  $params['name'],
                'group_id' => $params['group'],
                'request' => $params['request'],
                'param_explain' => $params['param_explain'],
                'result_text' => $params['result_text'],
                'result_explain' => $params['result_explain'],
                'user_id' => 1,
                'sort' => $params['sort'],
                'status' => $params['status']
            ]);

            $paramModel = new ParamModel();
            $paramModel->where('api_id','=',$params['id'])->delete();

            $data = [];

            $paramList = $params['param'];
            if(is_array($paramList) && !empty($paramList)){
                foreach($params['param'] as $k => $v){
                    $data[] = [
                        'api_id' => $params['id'],
                        'param' => $v['param_name'],
                        'filed_type' => $v['param_type'],
                        'must' => $v['must'],
                        'type' => 0,
                        'explain' => $v['explain']
                    ];
                }
            }

            if($data){
                $paramModel->saveAll($data);
            }

            $data = [];
            $resultList = $params['result'];
            if(is_array($resultList) && !empty($resultList)){
                foreach($resultList as $kk => $vv){
                    $data[] = [
                        'api_id' => $params['id'],
                        'param' => $vv['param_name'],
                        'filed_type' => $vv['param_type'],
                        'must' => $vv['must'],
                        'type' => 1,
                        'explain' => $vv['explain']
                    ];
                }
            }

            if($data){
                $paramModel->saveAll($data);
            }

        }catch(\Exception $e){
            logs($e->getMessage());
            $model->rollback();
            return ajaxReturn('API编辑失败');
        }
        $model->commit();
        return ajaxReturn([],'编辑成功');
    }


    public function api_status_edit_do(Request $request)
    {
        $param = $request->param();
        if(!$param['id']){
            return ajaxReturn('参数错误');
        }
        ApiModel::update([
            'id' => $param['id'],
            'status' => $param['status']
        ]);
        return ajaxReturn([]);
    }

    ///API参数编辑框
    public function param_edit(Request $request)
    {
        $param = $request->param();
        $list = ParamModel::all(['api_id'=>$param['id'],'type'=>$param['type']]);
        return $list ? ajaxReturn($list) : ajaxReturn('参数查询错误');
    }

    //API参数编辑处理
    public function param_edit_do(Request $request)
    {
        if(!$this->auth()){
            return ajaxReturn('请先登陆再进行操作');
        }
        $request = $request->param();
        $param = $request['param'];
        if(is_array($param) && !empty($param)){
            foreach($param as $k => $v){
                ParamModel::update([
                    'id' => $v['id'],
                    'filed_type' => $v['param_type'],
                    'must' => $v['must'],
                    'explain' => $v['explain']
                ]);
            }
        }
        return ajaxReturn([]);
    }

    //分组列表
    public function group()
    {
        if(!$this->isRoot()){
            $this->redirect('/admin');
        }
        return $this->fetch();
    }

    //分组数据获取
    public function group_data(Request $request)
    {
        $list = ApiGroupModel::paginate([
            'list_rows'=>$request->param("limit"),
            'page'=>$request->param("page")
            ]);
        if(is_array($list) || is_object($list)){
            return ajaxReturn($list->items(),'',$list->total());
        }else{
            return ajaxReturn('查询错误');
        }
    }

    //获取可用分组列表
    public function getGroupList(Request $request){
        $list = ApiGroupModel::all(function($query){
            $query->where(['status'=>1])->order("id desc");
        });
        return ajaxReturn($list);
    }

    //分组添加
    public function group_add(Request $request)
    {
        if(!$this->auth()){
            return ajaxReturn('请先登陆再进行操作');
        }
        $return = [];
        if($request->param("name")){
            $apiGroupModel = new ApiGroupModel(
                [
                    'name' => $request->param("name"),
                    'status' => $request->param("status") ? 1 : 0,
                    'create_time' => time()
                ]
            );
            $result = $apiGroupModel->save();
            if($result){
                $return = $result;
            }
        }
        return json($return);
    }



}
